package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;

import entity.MatchedLogRec;
import exceptions.SendDataException;

public class DataSender {
	private String ip;//采集系统服务器IP地址
	private int port;//采集系统服务器端口号
	private Socket socket;//建立到服务器的socket连接
	
	public DataSender() {
	}
	
	public DataSender(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}

	public void initSocket() throws SendDataException{
		try {
			socket = new Socket(ip,port);
		} catch (Exception e) {
			e.printStackTrace();
			throw new SendDataException(e);
		}
	}
	
	public void closeSocket() throws SendDataException{
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new SendDataException(e);
		}
	}
	
	public void send(List<MatchedLogRec> matchedLogs) throws SendDataException{
		try {
			initSocket();
			socket.setSoTimeout(5000);
			InputStream in = socket.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			OutputStream out = socket.getOutputStream();
			PrintWriter writer = new PrintWriter(new OutputStreamWriter(out));
			
			for (MatchedLogRec rec : matchedLogs) {
				while(true){
					writer.println(rec.tostring());//服务端会不会接收到重复的消息
					writer.flush();//灰常重要
					//readLine是阻塞的，socket.setSoTimeout(5000);设置阻塞时长，到时间出异常，捕获异常do nothing
					try {
						String echo =reader.readLine();//server可返回指定的成功信息，如“success”
						if("success".equals(echo)){//判断server返回的指定成功信息
							break;
						}
					} catch (Exception e) {}
				}
			}
			in.close();
			reader.close();
			out.close();
			writer.close();
			closeSocket();
		} catch (Exception e) {
			e.printStackTrace();
			throw new SendDataException(e);
		}
	}
}
